package se.sweco.ws;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Properties;

import javax.servlet.http.HttpServlet;

import org.apache.xml.serializer.DOMSerializer;
import org.apache.xml.serializer.Method;
import org.apache.xml.serializer.OutputPropertiesFactory;
import org.apache.xml.serializer.Serializer;
import org.apache.xml.serializer.SerializerFactory;
import org.w3c.dom.Document;


public abstract class AbstractServlet extends HttpServlet {
	protected static final String INVALID_PARAMS = "<response><error>Invalid parameters</error></response>";
	protected static final String DOCUMENT_ERROR = "<response><error>Failed to create document</error></response>";
	private static Properties props = OutputPropertiesFactory.getDefaultMethodProperties(Method.XML);
	private static Serializer ser = SerializerFactory.getSerializer(props);

	protected void writeString(PrintWriter out, String err) {
		out.println(err);
	}
	
	protected void writeDocument(PrintWriter out, Document doc) {
		StringWriter sw = new StringWriter();
		ser.setWriter(sw);
		try {
			DOMSerializer dser = ser.asDOMSerializer();
			dser.serialize(doc);
		} catch (IOException e) {
			writeString(out, DOCUMENT_ERROR);
			return;
		}

		out.write(sw.toString());
	}
}
